package org.zebra.tenant.satoken;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.zebra.satoken.LoginHelper;
import org.zebra.tenant.TenantIdAcquirer;
import org.zebra.tenant.TenantLoginUser;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author zhanghongbin
 */
@Slf4j
public class SaTokenTenantIdAcquirer extends TenantIdAcquirer {

    @Override
    public <T extends Serializable> T getTenantId(HttpServletRequest request) {
        T tenantId = super.getTenantId(request);
        if (tenantId == null) {
            return this.getTenantIdBySaToken();
        }
        return tenantId;
    }

    /**
     * 获取租户ID
     *
     * @return 租户id
     */
    public <T extends Serializable> T getTenantIdBySaToken() {
        TenantLoginUser loginUser = null;
        try {
            loginUser = (TenantLoginUser) LoginHelper.getLoginUser();
            if (loginUser != null) {
                return (T) loginUser.getTenantId();
            }
            loginUser = (TenantLoginUser) StpUtil.getExtra(LoginHelper.LOGIN_USER_KEY);
        } catch (Exception e) {
            log.info("getTenantIdBySaToken", e);
        }
        if (loginUser != null) {
            return (T) loginUser.getTenantId();
        }
        return null;
    }
}
